import { existsSync, readdirSync, readFileSync } from 'fs';
import { join } from 'path';
import { logger } from '../utils/logger';
import { events } from '../utils/events';
import { Room } from '../api/Room';
import { IModJSON } from './Mod';
import { CardRegistry } from '../registry/CardRegistry';

export class PoolLoader {
	constructor(readonly mod: IModJSON) {}

	loadPools(path: string) {
		if (!existsSync(path)) return;

		logger.info(`Loading card pools from: ${path}`);
		readdirSync(path).forEach((value) => {
			const filePath = join(path, value);
			try {
				const json = JSON.parse(readFileSync(filePath, 'utf-8'));
				this.register(json);
			} catch (error) {
				logger.error(`Error loading pool from ${filePath}: ${error}`);
			}
		});
	}

	private register(json: IPoolJSON) {
		for (const i in json) {
			json[i].forEach((card) => {
				CardRegistry.addPool(i, card.id, card.count);
			});
		}
	}
}

export interface IPoolJSON {
	[key: string]: { id: string; count: number }[];
}
